import { useState, useEffect, useRef } from 'react'
import { App, Descriptions, Space, Tabs, Image, Button, Table, Alert, Select, Radio, Modal } from 'antd'
import { useModel, useParams, request } from '@umijs/max'
import { CheckCircleOutlined } from '@ant-design/icons'
import { createXml, xmlFormat } from '@/utils/utils'
import YFMap from '@/utils/YFMap'
import xmlKey from '@/utils/xmlKey'
import styles from './OrderInfo.less'
import { getAccessToken, getPlatTypeFromDomain, getUnique } from '@/utils/utils'
import CreditBtnGroup from './CreditBtnGroup/CreditBtnGroup'
import OldCreditBtnGroup from './OldCreditBtnGroup/OldCreditBtnGroup'

const faceStatusMap = {
  1: '未审核',
  2: '通过',
  3: '未通过'
}
const telOperationMap = {
  1: '电信',
  2: '联通',
  3: '移动'
}
const telPeriodMap = {
  1: '0-6(个月)',
  2: '6-12(个月)',
  3: '12-24(个月)',
  4: '24+(个月)'
}
const groupNumMap = {
  a: '0-50人',
  b: '50-100人',
  c: '100-500人',
  d: '500+人'
}
const probeResMap = {
  1: '预期',
  2: '正常',
  3: '延期',
  4: '数据不充分'
}
let timer = null

export default () => {
  const { id } = useParams()
  const { message, modal } = App.useApp()
  const { platformType, userInfo, setIsLoading } = useModel('Global')
  const {
    GetOrderInfo,
    GetRisk,
    UserAuthenticationInfo,
    OrderExpress,
    LookContract,
    RefreshContract,
    GetCreditQueryTime,
    getIsOpenNotary,
    AuditOrder
  } = useModel('RiskControl')

  const { GetBasicSet } = useModel('BaseSet')
  const { GetPlatformCreditType } = useModel('Order')

  const [orderInfo, setOrderInfo] = useState(null)
  const [tabConfig, setTabConfig] = useState([])
  const [tabKey, setTabKey] = useState('0')
  const [clientInfoItem, setClientInfoItem] = useState([])
  const [buttonLoading, setButtonLoading] = useState(false)
  const [hasNotary, setHasNotary] = useState(false)
  const [creditData, setCreditData] = useState([])
  const [jinDunRiskContral, setJinDunRiskContral] = useState(null)
  const [leihuzuoRiskContral, setLeihuzuoRiskContral] = useState(null)

  const [riskControlData, setRiskControlData] = useState({})
  const [creditStatus, setCreditStatus] = useState(null)
  const [YFRiskControlReportItem, setYFRiskControlReportItem] = useState([])

  const [advancedDepositTerm, setAdvancedDepositTerm] = useState(0)
  const [contractType, setContractType] = useState(0)

  const [agreeModalFlag, setAgreeModalFlag] = useState(false)

  const orderInfoRef = useRef({})

  const [creditSwitch, setCreditSwitch] = useState(0) // 1公证征信 0雄懿征信

  const formatRender = (value, type = 'text', placeholder) => {
    if (type === 'text') {
      return value || placeholder || '-'
    } else if (type === 'img') {
      return value ? (
        <Image
          style={{
            width: '350px',
            height: '250px',
            objectFit: 'cover',
            borderRadius: '5px'
          }}
          src={value}
        ></Image>
      ) : (
        placeholder || '未上传'
      )
    } else {
      return value
    }
  }

  const renderTitle = title => {
    return (
      <div className={styles.desc_header}>
        <div className={styles.desc_header_text}>{title}</div>
        <div className={styles.desc_header_bg}></div>
        <div className={styles.desc_header_snd_bg}></div>
      </div>
    )
  }

  const renderCredit = data => {
    const isRow = !!data.filter(i => i.children && i.children.length).length

    return (
      <div className={isRow ? styles.row : styles['row-content']}>
        {data.map((item, index) =>
          item.children && item.children.length ? (
            <div key={index}>
              <div className={styles['row-title']}>{item.label}</div>
              {renderCredit(item.children)}
            </div>
          ) : (
            <div className={styles.row_line} key={index}>
              <div className={`${styles['row-content-box1']} ${styles.f}`}>{item.label}</div>
              <div className={`${styles['row-content-box2']} ${styles.f}`}>{item.value || '-'}</div>
            </div>
          )
        )}
      </div>
    )
  }

  // 用户信息渲染数据
  const userInfoDescItem = [
    {
      title: '用户信息',
      column: 3,
      noBordered: true,
      layout: 'vertical',
      items: [
        {
          key: 'username',
          label: '姓名',
          children: formatRender(riskControlData?.order?.username)
        },
        {
          key: 'cell',
          label: '身份证号码',
          children: formatRender(riskControlData?.order?.cell)
        },
        {
          key: 'mobile',
          label: '手机号',
          children: formatRender(riskControlData?.order?.mobile)
        }
      ]
    }
  ]

  // 风控报告渲染数据
  const riskControlReportItem = [
    {
      title: renderTitle('⼿机三要素简版—移动联通电信'),
      column: 3,
      layout: 'vertical',
      items: [
        {
          key: 'checkItem',
          label: '校验项',
          children: '⾝份证号 、 ⼿机号 、 姓名'
        },
        {
          key: 'telOperation',
          label: '⼿机号归属地',
          children: riskControlData.brData?.info_verify?.TelCheck_s?.operation
            ? telOperationMap[riskControlData.brData.info_verify.TelCheck_s.operation]
            : '其他'
        },
        {
          key: 'telCheckResult',
          label: '校验结果',
          children: riskControlData.brData?.info_verify?.TelCheck_s?.result
            ? riskControlData.brData.info_verify.TelCheck_s.result === '1'
              ? '⼀致'
              : '不⼀致'
            : '暂无数据'
        }
      ]
    },
    {
      title: renderTitle('手机在网时长'),
      column: 2,
      items: [
        {
          key: 'telOperationType',
          label: '运营商类型',
          children: riskControlData.brData?.info_verify?.TelPeriod?.operation
            ? telOperationMap[riskControlData.brData.info_verify.TelPeriod.operation]
            : '暂无数据'
        },
        {
          key: 'telPeriod',
          label: '⼿机在⽹时⻓区间',
          children: riskControlData.brData?.info_verify?.TelPeriod?.data?.value
            ? telPeriodMap[riskControlData.brData.info_verify.TelPeriod.data.value]
            : '暂无数据'
        }
      ]
    },
    {
      title: renderTitle('法院被执行人-高级版'),
      type: 'table',
      columns: [
        {
          title: '数据类型',
          dataIndex: 'datatype'
        },
        {
          title: '姓名',
          dataIndex: 'name'
        },
        {
          title: '案号',
          dataIndex: 'casenum'
        },
        {
          title: '省份',
          dataIndex: 'court'
        },
        {
          title: '命中等级',
          dataIndex: 'signalRating'
        },
        {
          title: '⽴案时间',
          dataIndex: 'time'
        },
        {
          title: '性别',
          dataIndex: 'sexname'
        },
        {
          title: '年龄',
          dataIndex: 'age'
        },
        {
          title: '执⾏法院',
          dataIndex: 'courtname'
        },
        {
          title: '地域名称',
          dataIndex: 'areaname'
        },
        {
          title: '命中等级',
          dataIndex: 'signalRating'
        },
        {
          title: '命中内容',
          dataIndex: 'signalDesc'
        },
        {
          title: '⽴案时间',
          dataIndex: 'regdate'
        }
      ],
      dataSource: riskControlData.brData?.load_verify?.ExecutionPro
        ? Object.keys(riskControlData.brData.load_verify.ExecutionPro).map(i => ({
            id: i,
            ...riskControlData.brData.load_verify.ExecutionPro[i]
          }))
        : []
    },
    {
      title: renderTitle('偿债压力指数'),
      items: [
        {
          key: 'nodebtscore',
          label: '偿债压⼒指数',
          children: riskControlData.brData?.load_verify?.DebtRepayStress?.nodebtscore || '暂无数据'
        }
      ]
    },
    {
      title: renderTitle('团伙欺诈排查'),
      items: [
        {
          key: 'list_level',
          label: '⻛险等级',
          children: riskControlData.brData?.load_verify?.FraudRelation_g?.list_level || '-'
        },
        {
          key: 'list_level',
          label: '团伙规模',
          children: riskControlData.brData?.load_verify?.FraudRelation_g?.group_num
            ? groupNumMap[riskControlData.brData.load_verify.FraudRelation_g.group_num]
            : '暂无数据'
        }
      ]
    },
    {
      title: renderTitle('特殊名单验证'),
      type: 'table',
      columns: [
        {
          title: '命中特殊名单',
          dataIndex: 'key'
        },
        {
          title: '取值结果',
          dataIndex: 'value',
          render: (text, record) => {
            // 存疑
            text >= 1 ? '命中' : '未命中'
          }
        }
      ],
      dataSource: riskControlData.brData?.load_verify?.specialList_c || []
    },
    {
      title: renderTitle('特殊名单验证'),
      type: 'table',
      columns: [
        {
          title: '机构类型/时间',
          dataIndex: 'date'
        },
        {
          title: '近7天',
          children: [
            {
              title: '机构数',
              dataIndex: 'mechanismAmount_7',
              key: 'mechanismAmount_7'
            },
            {
              title: '次数',
              dataIndex: 'times_7',
              key: 'times_7'
            }
          ]
        },
        {
          title: '近15天',
          children: [
            {
              title: '机构数',
              dataIndex: 'mechanismAmount_7',
              key: 'mechanismAmount_7'
            },
            {
              title: '次数',
              dataIndex: 'times_7',
              key: 'times_7'
            }
          ]
        },
        {
          title: '近1个月',
          children: [
            {
              title: '机构数',
              dataIndex: 'mechanismAmount_7',
              key: 'mechanismAmount_7'
            },
            {
              title: '次数',
              dataIndex: 'times_7',
              key: 'times_7'
            }
          ]
        },
        {
          title: '近3个月',
          children: [
            {
              title: '机构数',
              dataIndex: 'mechanismAmount_7',
              key: 'mechanismAmount_7'
            },
            {
              title: '次数',
              dataIndex: 'times_7',
              key: 'times_7'
            }
          ]
        },
        {
          title: '近6个月',
          children: [
            {
              title: '机构数',
              dataIndex: 'mechanismAmount_7',
              key: 'mechanismAmount_7'
            },
            {
              title: '次数',
              dataIndex: 'times_7',
              key: 'times_7'
            }
          ]
        },
        {
          title: '近12个月',
          children: [
            {
              title: '机构数',
              dataIndex: 'mechanismAmount_7',
              key: 'mechanismAmount_7'
            },
            {
              title: '次数',
              dataIndex: 'times_7',
              key: 'times_7'
            }
          ]
        }
      ],
      dataSource: riskControlData.brData?.load_verify?.specialList_c || []
    }
  ]

  // 消费能力报告渲染数据
  const spendAbilityReportItem = [
    {
      title: renderTitle('工作稳定性评分'),
      column: 3,
      layout: 'vertical',
      items: [
        {
          key: 'income_model',
          label: '收入评分',
          children: riskControlData.cycData?.stable_wealth?.income_model || '暂无数据'
        },
        {
          key: 'stable_model',
          label: '稳定性评分',
          children: riskControlData.cycData?.stable_wealth?.stable_model || '暂无数据'
        },
        {
          key: 'historical_pattern',
          label: '历史情况评分',
          children: riskControlData.cycData?.stable_wealth?.historical_pattern || '暂无数据'
        }
      ]
    }
  ]

  // 探针渲染数据
  const probeItem = [
    {
      title: renderTitle('探针数据'),
      column: 1,
      items: [
        {
          key: 'result_code',
          label: '探查结果编码',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.result_code
            ? probeResMap[riskControlData.probeData?.data?.data?.data?.result_detail.result_code]
            : '-'
        },
        {
          key: 'max_overdue_amt',
          label: '最大逾期金额',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.max_overdue_amt || '-'
        },
        {
          key: 'max_overdue_days',
          label: '最长逾期天数',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.max_overdue_days || '-'
        },
        {
          key: 'latest_overdue_time',
          label: '最近逾期时间',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.latest_overdue_time || '-'
        },
        {
          key: 'max_performance_amt',
          label: '最大履约金额',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.max_performance_amt || '-'
        },
        {
          key: 'latest_performance_time',
          label: '最近履约时间',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.latest_performance_time || '-'
        },
        {
          key: 'count_performance',
          label: '履约笔数',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.count_performance || '-'
        },
        {
          key: 'currently_overdue',
          label: '当前逾期机构数',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.currently_overdue || '-'
        },
        {
          key: 'currently_performance',
          label: '当前履约机构数',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.currently_performance || '-'
        },
        {
          key: 'acc_exc',
          label: '异常还款机构数',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.acc_exc || '-'
        },
        {
          key: 'acc_sleep',
          label: '睡眠机构数',
          children: riskControlData.probeData?.data?.data?.data?.result_detail.acc_sleep || '-'
        }
      ]
    }
  ]

  // 全景雷达渲染数据
  const radarItem = [
    {
      title: '申请雷达报告详情',
      key: 'apply_report_detail',
      children: [
        { label: '申请准入分', key: 'A22160001' },
        { label: '申请准入置信度', key: 'A22160002' },
        { label: '申请命中机构数', key: 'A22160003' },
        { label: '申请命中消金类机构数', key: 'A22160004' },
        { label: '申请命中网络贷款类机构数', key: 'A22160005' },
        { label: '机构总查询次数', key: 'A22160006' },
        { label: '最近一次查询时间', key: 'A22160007' },
        { label: '近1个月机构总查询笔数', key: 'A22160008' },
        { label: '近3个月机构总查询笔数', key: 'A22160009' },
        { label: '近6个月机构总查询笔数', key: 'A22160010' }
      ]
    },
    {
      title: '行为雷达报告详情',
      key: 'behavior_report_detail',
      children: [
        { label: '贷款行为分', key: 'B22170001' },
        { label: '近1个月贷款笔数', key: 'B22170002' },
        { label: '近3个月贷款笔数', key: 'B22170003' },
        { label: '近6个月贷款笔数', key: 'B22170004' },
        { label: '近12个月贷款笔数', key: 'B22170005' },
        { label: '近24个月贷款笔数', key: 'B22170006' },
        { label: '近1个月贷款总金额', key: 'B22170007' },
        { label: '近3个月贷款总金额', key: 'B22170008' },
        { label: '近6个月贷款总金额', key: 'B22170009' },
        { label: '近12个月贷款总金额', key: 'B22170010' },
        { label: '近24个月贷款总金额', key: 'B22170011' },
        { label: '近12个月贷款金额在1k及以下的笔数', key: 'B22170012' },
        { label: '近12个月贷款金额在1k-3k的笔数', key: 'B22170013' },
        { label: '近12个月贷款金额在3k-10k的笔数', key: 'B22170014' },
        { label: '近12个月贷款金额在1w以上的笔数', key: 'B22170015' },
        { label: '近1个月贷款机构数', key: 'B22170016' },
        { label: '近3个月贷款机构数', key: 'B22170017' },
        { label: '近6个月贷款机构数', key: 'B22170018' },
        { label: '近12个月贷款机构数', key: 'B22170019' },
        { label: '近24个月贷款机构数', key: 'B22170020' },
        { label: '近12个月消金类贷款机构数', key: 'B22170021' },
        { label: '近24个月消金类贷款机构数', key: 'B22170022' },
        { label: '近12个月网贷类贷款机构数', key: 'B22170023' },
        { label: '近24个月网贷类贷款机构数', key: 'B22170024' },
        { label: '近6个月M0+逾期贷款笔数', key: 'B22170025' },
        { label: '近12个月M0+逾期贷款笔数', key: 'B22170026' },
        { label: '近24个月M0+逾期贷款笔数', key: 'B22170027' },
        { label: '近6个月M1+逾期贷款笔数', key: 'B22170028' },
        { label: '近12个月M1+逾期贷款笔数', key: 'B22170029' },
        { label: '近24个月M1+逾期贷款笔数', key: 'B22170030' },
        { label: '近6个月累计逾期金额', key: 'B22170031' },
        { label: '近12个月累计逾期金额', key: 'B22170032' },
        { label: '近24个月累计逾期金额', key: 'B22170033' },
        { label: '正常还款订单数占贷款总订单数比例', key: 'B22170034' },
        { label: '近1个月失败扣款笔数', key: 'B22170035' },
        { label: '近3个月失败扣款笔数', key: 'B22170036' },
        { label: '近6个月失败扣款笔数', key: 'B22170037' },
        { label: '近12个月失败扣款笔数', key: 'B22170038' },
        { label: '近24个月失败扣款笔数', key: 'B22170039' },
        { label: '近1个月履约贷款总金额', key: 'B22170040' },
        { label: '近3个月履约贷款总金额', key: 'B22170041' },
        { label: '近6个月履约贷款总金额', key: 'B22170042' },
        { label: '近12个月履约贷款总金额', key: 'B22170043' },
        { label: '近24个月履约贷款总金额', key: 'B22170044' },
        { label: '近1个月履约贷款次数', key: 'B22170045' },
        { label: '近3个月履约贷款次数', key: 'B22170046' },
        { label: '近6个月履约贷款次数', key: 'B22170047' },
        { label: '近12个月履约贷款次数', key: 'B22170048' },
        { label: '近24个月履约贷款次数', key: 'B22170049' },
        { label: '最近一次履约距今天数', key: 'B22170050' },
        { label: '贷款行为置信度', key: 'B22170051' },
        { label: '贷款已结清订单数', key: 'B22170052' },
        { label: '信用贷款时长', key: 'B22170053' },
        { label: '最近一次贷款放款时间', key: 'B22170054' }
      ]
    },
    {
      title: '信用现状报告详情',
      key: 'current_report_detail',
      children: [
        { label: '网贷授信额度', key: 'C22180001' },
        { label: '网贷额度置信度', key: 'C22180002' },
        { label: '网络贷款类机构数', key: 'C22180003' },
        { label: '网络贷款类产品数', key: 'C22180004' },
        { label: '网络贷款机构最大授信额度', key: 'C22180005' },
        { label: '网络贷款机构平均授信额度', key: 'C22180006' },
        { label: '消金贷款类机构数', key: 'C22180007' },
        { label: '消金贷款类产品数', key: 'C22180008' },
        { label: '消金贷款类机构最大授信额度', key: 'C22180009' },
        { label: '消金贷款类机构平均授信额度', key: 'C22180010' },
        { label: '消金建议授信额度', key: 'C22180011' },
        { label: '消金额度置信度', key: 'C22180012' }
      ]
    }
  ].map(i => ({
    title: renderTitle(i.title),
    column: 2,
    items: i.children.map(it => ({
      ...it,
      children: riskControlData.radarData?.data?.data?.data?.result_detail[i.key][it.key] || '-'
    }))
  }))

  const renderList = (listData = []) => {
    return listData.map((item, index) => {
      const { type, title, items, key = index, column, noBordered, layout, columns, dataSource } = item
      return type === 'table' ? (
        <div style={{ marginTop: '20px' }} key={key}>
          {title}
          <Table
            columns={columns}
            dataSource={dataSource}
            pagination={false}
            rowKey='id'
            key={key}
            bordered
            className={styles.table}
          ></Table>
        </div>
      ) : (
        <Descriptions
          title={title}
          items={items}
          key={key}
          column={column || 2}
          bordered={!noBordered}
          layout={layout || 'horizontal'}
        ></Descriptions>
      )
    })
  }

  const tabItems = [
    {
      key: '0',
      label: '客户详情',
      children: (
        <>
          <div>{renderList(clientInfoItem)}</div>
        </>
      )
    },
    {
      key: '7',
      label: '金盾风控',
      children: (
        <>
          {jinDunRiskContral ? (
            jinDunRiskContral.data ? (
              <div className={styles.img_wrapper}>
                <Image className={styles.img_content} preview={false} src={jinDunRiskContral.data}></Image>
              </div>
            ) : (
              <Alert message={jinDunRiskContral.msg} type='warning'></Alert>
            )
          ) : (
            <Alert message='加载中' type='info'></Alert>
          )}
        </>
      )
    },
    {
      key: '17',
      label: '金盾-至臻版',
      children: (
        <>
          {jinDunRiskContral ? (
            jinDunRiskContral.data ? (
              <div className={styles.img_wrapper}>
                <Image className={styles.img_content} preview={false} src={jinDunRiskContral.data}></Image>
              </div>
            ) : (
              <Alert message={jinDunRiskContral.msg} type='warning'></Alert>
            )
          ) : (
            <Alert message='加载中' type='info'></Alert>
          )}
        </>
      )
    },
    {
      key: '1',
      label: '风控报告',
      children: (
        <>
          {renderList(userInfoDescItem)}
          <div className={styles.style_wrapper}>{renderList(riskControlReportItem)}</div>
        </>
      )
    },
    {
      key: '2',
      label: '消费能力报告',
      children: (
        <>
          {renderList(userInfoDescItem)}
          <div className={styles.style_wrapper}>{renderList(spendAbilityReportItem)}</div>
        </>
      )
    },
    {
      key: '4',
      label: '探针',
      children: (
        <>
          {renderList(userInfoDescItem)}
          {riskControlData.probeData?.data?.data?.data ? (
            riskControlData.probeData?.data?.data?.data.code === '0' ? (
              <div className={styles.style_wrapper}>{renderList(probeItem)}</div>
            ) : (
              riskControlData.probeData?.data?.data?.data.desc
            )
          ) : (
            '暂无数据'
          )}
        </>
      )
    },
    {
      key: '5',
      label: '全景雷达',
      children: (
        <>
          {renderList(userInfoDescItem)}
          {riskControlData.radarData?.data?.data?.data ? (
            riskControlData.radarData?.data?.data?.data.code === '0' ? (
              <div className={styles.style_wrapper}>{renderList(radarItem)}</div>
            ) : (
              riskControlData.radarData?.data?.data?.data.desc
            )
          ) : (
            '暂无数据'
          )}
        </>
      )
    },
    {
      key: '16',
      label: '优分风控',
      children: (
        <>
          {renderList(userInfoDescItem)}
          <div className={styles.style_wrapper}>{renderList(YFRiskControlReportItem)}</div>
        </>
      )
    },
    {
      key: '14',
      label: '微盾风控',
      children: (
        <>
          {leihuzuoRiskContral ? (
            leihuzuoRiskContral.data ? (
              <div className={styles.iframe_wrapper}>
                <iframe src={leihuzuoRiskContral.data} width='100%' height='100%'></iframe>
              </div>
            ) : (
              <Alert message={leihuzuoRiskContral.msg} type='warning'></Alert>
            )
          ) : (
            <Alert message='加载中' type='info'></Alert>
          )}
        </>
      )
    }
  ]

  useEffect(() => {
    getTabConfig()
    getOrderInfo()
    checkNotary()
    GetPlatformCredit()
  }, [])

  // 获取新、老征信开关
  const GetPlatformCredit = async () => {
    const res = await GetPlatformCreditType()
    if (res) {
      setCreditSwitch(res?.is_notary_credit)
    }
  }

  useEffect(() => {
    if (orderInfo) {
      setClientInfoItem(formatClientInfoItem())
    }
  }, [orderInfo, buttonLoading])

  useEffect(() => {
    setRiskControlData({})
    setJinDunRiskContral(null)
    if (tabKey === '6') {
      getCreditStatus()
    } else if (tabKey !== '0') {
      getRiskControlInfo()
    }
  }, [tabKey])

  const getTabConfig = async () => {
    const res = await GetBasicSet()
    if (res && res.risk_type) {
      setTabConfig(res.risk_type)
    }
  }

  const checkNotary = async () => {
    const res = await getIsOpenNotary()
    setHasNotary(res)
  }

  const getCreditStatus = async () => {
    setCreditStatus(null)
    setIsLoading(true)
    const res = await GetCreditQueryTime({
      user_id: orderInfoRef.current.user_id,
      deduction: tabKey,
      merchant_id: userInfo.merchant_id
    })
    setIsLoading(false)
    if (res) {
      setCreditStatus(res)
      if (res.is_auth === 2 && res.is_query === 3) {
        getRiskControlInfo()
      }
    }
  }

  // 客户详情渲染数据
  const formatClientInfoItem = () => {
    return [
      {
        key: 'orderInfo',
        title: `订单信息 订单号：${orderInfo.order_sn || '-'}`,
        items: [
          {
            key: 'user_id',
            label: '用户ID',
            children: formatRender(orderInfo.user_id)
          },
          {
            key: 'goods_id',
            label: '商品ID',
            children: formatRender(orderInfo.goods_id)
          },
          {
            key: 'status_desc',
            label: '订单状态',
            children: formatRender(orderInfo.status_desc)
          },
          {
            key: 'created_at',
            label: '创建时间',
            children: formatRender(orderInfo.created_at)
          },
          {
            key: 'address',
            label: '收货地址',
            children: formatRender(orderInfo.address)
          },
          {
            key: 'cert_name',
            label: '下单人姓名',
            children: formatRender(orderInfo.cert_name)
          },
          {
            key: 'use_rec_name',
            label: '收货人姓名',
            children: formatRender(orderInfo.use_rec_name)
          },
          {
            key: 'tel',
            label: '收货人手机号',
            children: formatRender(orderInfo.tel)
          },
          {
            key: 'city',
            label: '下单定位地址',
            children: formatRender(orderInfo.city)
          }
        ]
      },
      {
        key: 'productInfo',
        title: '商品信息',
        items: [
          {
            key: 'goods_name',
            label: '商品名称',
            children: formatRender(orderInfo.goods_name)
          },
          {
            key: 'selling_price',
            label: '官方指导价',
            children: formatRender(orderInfo.selling_price)
          },
          {
            key: 'attr_value',
            label: '套餐信息',
            children: formatRender(orderInfo.attr_value)
          }
        ]
      },
      {
        key: 'rentInfo',
        title: '租赁信息',
        items: [
          {
            key: 'attr_value',
            label: '租赁期数',
            children: formatRender(orderInfo.lease_term + '期')
          },
          {
            key: 'per_term_price',
            label: '每期租赁价格',
            children: formatRender(orderInfo.per_term_price)
          },
          {
            key: 'free_money',
            label: '预授权总金额',
            children: formatRender(orderInfo.free_money)
          },
          {
            key: 'attr_value',
            label: '待付租金',
            children: (Number(orderInfo.total_price) - Number(orderInfo.had_pay)).toFixed(2)
          },
          {
            key: 'buy_out_price',
            label: '商品买断价',
            children: formatRender(orderInfo.buy_out_price)
          },
          {
            key: 'first_pay',
            label: '商品首期付款',
            children: formatRender(orderInfo.first_pay)
          },
          {
            key: 'buy_out_to_pay',
            label: '当前买断款',
            children: formatRender(orderInfo.buy_out_to_pay)
          },
          {
            key: 'total_rent',
            label: '总租金',
            children: formatRender(orderInfo.total_rent)
          },
          {
            key: 'had_pay',
            label: '已收租金',
            children: formatRender(orderInfo.had_pay)
          },
          {
            key: 'lease_time',
            label: '当前租期',
            children: formatRender(orderInfo.lease_time)
          },
          {
            key: 'attr_value',
            label: '免押额度',
            children: formatRender(orderInfo.credit_amount)
          },
          // {
          //   key: 'attr_value',
          //   label: '押金',
          //   children: formatRender(orderInfo.freez_amount)
          // },
          // {
          //   key: 'attr_value',
          //   label: '押金',
          //   children: formatRender(orderInfo.freez_amount)
          // },
          ...orderInfo.orders_gain.map(gain => ({
            key: gain.id,
            label: gain.gain_name,
            children: `${gain.amount}元`
          }))
        ]
      },
      {
        key: 'realNameInfo',
        title: '实名信息',
        column: 1,
        items: [
          {
            key: 'cert_info',
            label: '身份证信息',
            children: (
              <Space>
                {formatRender(orderInfo.card_img, 'img', '未上传')}
                {formatRender(orderInfo.card_back_img, 'img', '未上传')}
              </Space>
            )
          },
          // {
          //   key: 'face_img',
          //   label: '人脸照片',
          //   children: formatRender(orderInfo.face_img, 'img', '照片未上传')
          // },
          {
            key: 'face_status',
            label: '人脸核验状态',
            children: faceStatusMap[orderInfo.face_status]
          }
        ]
      },
      {
        key: 'alipayInfo',
        title: '支付宝认证信息',
        items: [
          {
            key: 'cert_name',
            label: '认证姓名',
            children: formatRender(orderInfo.cert_name)
          },
          {
            key: 'cert_no',
            label: '身份证号',
            children: formatRender(orderInfo.cert_no)
          },
          {
            key: 'sex',
            label: '性别',
            children: formatRender(orderInfo.sex)
          },
          {
            key: 'age',
            label: '年龄',
            children: formatRender(orderInfo.age)
          },
          {
            key: 'shengxiao',
            label: '生肖',
            children: formatRender(orderInfo.shengxiao)
          },
          {
            key: 'user_info_user_id',
            label: '支付宝用户唯一id',
            children: formatRender(orderInfo.user_info_user_id)
          }
        ]
      },
      {
        key: 'logisticsInfo',
        title: '物流信息',
        items: [
          {
            key: 'companyName',
            label: '物流公司',
            children: formatRender(orderInfo.companyName, 'text', '未上传物流单号，无法查询')
          },
          {
            key: 'nu',
            label: '物流单号',
            children: formatRender(orderInfo.nu, 'text', '未上传物流单号，无法查询')
          },
          {
            key: 'shipping_method_desc',
            label: '配送方式',
            children: formatRender(orderInfo.shipping_method_desc, 'text', '未上传物流单号，无法查询')
          }
        ]
      },
      {
        key: 'returnInfo',
        title: '订单归还信息',
        items: [
          {
            key: 'return_companyName',
            label: '物流公司',
            children: '暂无数据'
          },
          {
            key: 'return_nu',
            label: '物流单号',
            children: '暂无数据'
          }
        ]
      },
      {
        key: 'contractOptions',
        title: '合同',
        items: [
          {
            key: 'contract',
            label: '查看与下载',
            children: (
              <Space>
                <Button onClick={() => contractOptions('check')} loading={buttonLoading} type='primary'>
                  查看合同
                </Button>
                <Button onClick={() => contractOptions('download')} loading={buttonLoading} type='primary'>
                  下载合同
                </Button>
                <Button onClick={recontract} type='primary' loading={buttonLoading} danger>
                  重新生成合同
                </Button>
              </Space>
            )
          }
        ]
      },
      {
        key: 'creditOptions',
        title: '征信',
        items: [
          {
            key: 'credit',
            label: '征信操作',
            children: (
              <Space direction='vertical'>
                {creditSwitch === 1 ? (
                  <CreditBtnGroup
                    user_id={orderInfo.user_id}
                    order_sn={orderInfo.order_sn}
                    leaseTerm={orderInfo.lease_term}
                  />
                ) : (
                  <OldCreditBtnGroup leaseTerm={orderInfo.lease_term} />
                )}
              </Space>
            )
          }
        ]
      },
      platformType && (orderInfo.status === 2100 || orderInfo.status === 2000)
        ? {
            key: 'options',
            title: '审核',
            items: [
              {
                key: 'audit',
                label: '审核操作',
                children: (
                  <Space>
                    <Button onClick={handleRefuse} loading={buttonLoading} type='primary' danger>
                      审核拒绝
                    </Button>
                    <Button onClick={handleAgree} loading={buttonLoading} type='primary'>
                      审核通过
                    </Button>
                  </Space>
                )
              }
            ]
          }
        : null
    ].filter(i => i)
  }

  const changeContractType = e => {
    console.log(changeContractType, e.target.value)
    setContractType(e.target.value)
  }

  const AgreeModalContent = () => {
    return (
      <Space direction='vertical'>
        {hasNotary ? (
          <Space direction='vertical'>
            <Space>
              <b>合同类型：</b>
              <Radio.Group onChange={changeContractType} value={contractType}>
                <Radio value={0}>普通合同</Radio>
                <Radio value={1}>公证合同</Radio>
              </Radio.Group>
            </Space>
            {contractType ? (
              <Space>
                <b>预付押金期数：</b>
                <Select
                  defaultValue={advancedDepositTerm}
                  onChange={val => setAdvancedDepositTerm(val)}
                  options={[
                    { label: '无', value: 0 },
                    { label: '1期', value: 1 },
                    { label: '2期', value: 2 },
                    { label: '3期', value: 3 },
                    { label: '4期', value: 4 },
                    { label: '5期', value: 5 },
                    { label: '6期', value: 6 }
                  ]}
                ></Select>
              </Space>
            ) : null}
          </Space>
        ) : null}
        <div>确认审核通过后，订单将继续流转，请确认是否通过</div>
      </Space>
    )
  }

  const handleRefuse = () => {
    setLoading()
    modal.confirm({
      title: '审核拒绝',
      content: '审核拒绝后，订单将关闭且无法继续，请确认是否拒绝',
      okText: '确认拒绝',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        clearLoading()
        handleAudit(3)
      }
    })
  }

  const handleAgree = () => {
    checkNotary()
    setLoading()
    setAgreeModalFlag(true)
  }

  const handleAudit = async type => {
    const params = {
      order_id: orderInfoRef.current.id,
      deal_status: type,
      advanced_deposit_term: advancedDepositTerm,
      contract_type: contractType
    }

    const res = await AuditOrder(params)
    if (res) {
      setAdvancedDepositTerm(0)
      setContractType(0)
      message.success('处理成功')
      getOrderInfo()
      setAgreeModalFlag(false)
    }
  }

  const setLoading = () => {
    setButtonLoading(true)
    timer = setTimeout(() => {
      setButtonLoading(false)
    }, 1000)
  }

  const clearLoading = () => {
    setButtonLoading(false)
    clearTimeout(timer)
    timer = null
  }

  const confirmRecontract = async () => {
    const res = await RefreshContract({ order_sn: orderInfoRef.current.order_sn })
    if (res) {
      message.success('合同已重新生成，请查看或下载新合同')
    }
  }

  const recontract = () => {
    setLoading()
    modal.confirm({
      title: '重新生成合同',
      content: '重新生成合同会已新内容覆盖合同现有盖章、签约日期以及起诉法院等内容，确定要重新生成合同么？',
      okButtonProps: {
        danger: true
      },
      okText: '确认重新生成',
      onOk: confirmRecontract
    })
  }

  const contractOptions = async type => {
    setLoading()
    const contractUrl = await LookContract({ order_id: orderInfoRef.current.id })
    clearLoading()
    if (contractUrl && contractUrl.url) {
      if (type === 'check') {
        const url = contractUrl.url
        let tempUrlArr = []
        if (Array.isArray(url)) {
          tempUrlArr = url
        } else {
          tempUrlArr = [url]
        }
        modal.info({
          title: '查看合同',
          icon: null,
          width: 1000,
          closable: true,
          okText: '下载合同',
          onOk: () => contractOptions('download'),
          content: (
            <Space direction='vertical'>
              {tempUrlArr.map((contract, contractIndex) => {
                let frameId = contractIndex + 1
                return <iframe src={contract} id={frameId} width='800px' height='500px'></iframe>
              })}
            </Space>
          )
        })
      } else if (type === 'download') {
        const url = `https://mpapi.zwzj66.com/api/best/downContract?order_sn=${
          orderInfoRef.current.order_sn
        }&token=${getAccessToken(getPlatTypeFromDomain())}`
        request(url, {
          method: 'GET',
          hideNotice: true
        }).then(res => {
          window.open(url)
        })
      }
    } else {
      message.warning('合同签约中，请稍后再试')
    }
  }

  const getOrderInfo = async () => {
    setIsLoading(true)
    const res = await GetOrderInfo({ id })
    setIsLoading(false)
    if (res) {
      setOrderInfo(res)
      orderInfoRef.current = res

      getBuyerInfo()
      getExpressInfo()
    }
  }

  const getBuyerInfo = async () => {
    const res = await UserAuthenticationInfo({ user_id: orderInfoRef.current.user_id })
    if (res) {
      const data = {
        ...res,
        ...orderInfoRef.current
      }
      setOrderInfo(data)
      orderInfoRef.current = data
    }
  }

  const getExpressInfo = async () => {
    const res = await OrderExpress({ order_id: orderInfoRef.current.id }, true)
    if (res) {
      const data = {
        ...res,
        ...orderInfoRef.current
      }
      setOrderInfo(data)
      orderInfoRef.current = data
    }
  }

  const formatYfData = youfenData => {
    const formatValue = (key, valueKey) => {
      const curItem = youfenData.find(i => i.type === key)
      let value = ''
      if (curItem.result.resCode !== '0000') {
        value = curItem.result.data.resMsg
      } else if (curItem.result.data.statusCode !== '2012') {
        value = curItem.result.data.statusMsg
      } else {
        value = YFMap[key]
          ? YFMap[key][curItem.result.data.result[valueKey]] || curItem.result.data.result[valueKey] || '-'
          : curItem.result.data.result[valueKey] || '-'
      }
      return value
    }

    const typeList = ['attention_list', 'general_risk', 'point_general', 'suspected_card', 'inquiry']
    const comprehensive = {
      title: renderTitle('综合评审'),
      column: 5,
      layout: 'vertical',
      items: [
        {
          key: 'attention_list',
          label: '重点关注人员评分',
          children: formatValue('attention_list', 'score')
        },
        {
          key: 'general_risk',
          label: '综合风险验证',
          children: formatValue('general_risk', 'msg')
        },
        {
          key: 'point_general',
          label: '优信分',
          children: formatValue('point_general', 'score')
        },
        {
          key: 'suspected_card',
          label: '疑似养卡核验',
          children: formatValue('suspected_card', 'status')
        }
      ]
    }

    const res = [
      comprehensive,
      ...youfenData
        .filter(i => !typeList.includes(i.type))
        .map(i => {
          const { result, type } = i

          const obj = {
            title: renderTitle(YFMap.title_map[type]),
            keyName: type
          }

          if (result.resCode === '0000') {
            if (result.data.statusCode === '2012') {
              if (type === 'multi_loan_check') {
                obj.type = 'combination'
                obj.column = 4
                obj.layout = 'vertical'

                const descData = result.data.result
                const tableList = descData.data
                delete descData.data
                delete descData.code

                obj.items = [
                  ...Object.keys(descData).map((item, index) => ({
                    key: index,
                    label: YFMap[type] ? YFMap[type][item] : item,
                    children: descData[item] || '-'
                  })),
                  {
                    key: 'cycle',
                    label: YFMap[type].cycle,
                    children: tableList[Object.keys(tableList)[0]].cycle
                  }
                ]

                obj.columns = [
                  {
                    title: '信贷平台注册详情',
                    dataIndex: 'S002',
                    render: item =>
                      item ? (
                        <>
                          <div>平台类型：{YFMap[type][item.platformType]}</div>
                          <div>平台代码：{item.platformCode}</div>
                          <div>注册时间：{item.registerTime}</div>
                        </>
                      ) : (
                        '-'
                      )
                  },
                  {
                    title: '贷款申请详情',
                    dataIndex: 'S004',
                    render: item =>
                      item ? (
                        <>
                          <div>平台类型：{YFMap[type][item.platformType]}</div>
                          <div>平台代码：{item.platformCode}</div>
                          <div>申请时间：{item.applicationTime}</div>
                          <div>申请金额区间：{item.applicationAmount}</div>
                          <div>申请结果：{item.applicationResult}</div>
                        </>
                      ) : (
                        '-'
                      )
                  },
                  {
                    title: '贷款放款详情',
                    dataIndex: 'S007',
                    render: item =>
                      item ? (
                        <>
                          <div>平台类型：{YFMap[type][item.platformType]}</div>
                          <div>平台代码：{item.platformCode}</div>
                          <div>放款时间：{item.loanLendersTime}</div>
                          <div>放款金额区间：{item.loanLendersAmount}</div>
                        </>
                      ) : (
                        '-'
                      )
                  },
                  {
                    title: '贷款驳回详情',
                    dataIndex: 'S009',
                    render: item =>
                      item ? (
                        <>
                          <div>平台类型：{YFMap[type][item.platformType]}</div>
                          <div>平台代码：{item.platformCode}</div>
                          <div>驳回时间：{item.rejectionTime}</div>
                        </>
                      ) : (
                        '-'
                      )
                  },
                  {
                    title: '逾期平台详情查询',
                    dataIndex: 'S012',
                    render: item =>
                      item ? (
                        <>
                          <div>逾期数量：{item.counts}</div>
                          <div>逾期金额区间：{item.money}</div>
                          <div>平台代码：{item.platformCode}</div>
                          <div>最近逾期时间：{item.dTime}</div>
                        </>
                      ) : (
                        '-'
                      )
                  },
                  {
                    title: '欠款查询',
                    dataIndex: 'S013',
                    render: item =>
                      item ? (
                        <>
                          <div>欠款金额区间：{item.money}</div>
                          <div>平台代码：{item.platformCode}</div>
                        </>
                      ) : (
                        '-'
                      )
                  }
                ]

                let dataSource = []
                Object.keys(tableList).forEach(tk => {
                  const ti = tableList[tk]
                  if (ti.data.length) {
                    ti.data.forEach((itm, idx) => {
                      if (dataSource[idx]) {
                        dataSource[idx][tk] = itm
                      } else {
                        dataSource[idx] = {
                          id: getUnique(),
                          [tk]: itm
                        }
                      }
                    })
                  }
                })
                obj.dataSource = dataSource
              } else if (type === 'inquiry') {
                obj.type = 'combination'
                obj.column = 5
                obj.layout = 'vertical'

                const descData = result.data.result
                const tableList = descData.list
                delete descData.list

                obj.items = Object.keys(descData).map((item, index) => ({
                  key: index,
                  label: YFMap[type] ? YFMap[type][item] : item,
                  children: descData[item] || '-'
                }))

                obj.columns = [
                  {
                    title: '文书编号',
                    dataIndex: 'id'
                  },
                  {
                    title: '时间',
                    dataIndex: 'caseTime'
                  },
                  {
                    title: '内容概要',
                    dataIndex: 'content'
                  },
                  {
                    title: '标题',
                    dataIndex: 'title'
                  },
                  {
                    title: '数据类型',
                    dataIndex: 'dataType'
                  },
                  {
                    title: '匹配度',
                    dataIndex: 'matchRatio'
                  }
                ]

                obj.dataSource = tableList
              } else if (type === 'blacklist_plus') {
                obj.type = 'table'
                obj.columns = [
                  {
                    title: '查询维度',
                    dataIndex: 'dimension'
                  },
                  {
                    title: '最新欺诈／风险状态',
                    dataIndex: 'lastCondition',
                    render: text => {
                      return YFMap[type][text] || text || '-'
                    }
                  },
                  {
                    title: '贷款类型',
                    dataIndex: 'loanTypes',
                    render: text => {
                      return YFMap[type][text] || text || '-'
                    }
                  },
                  {
                    title: '黑名单类型',
                    dataIndex: 'level',
                    render: text => {
                      return YFMap[type][text] || text || '-'
                    }
                  },
                  {
                    title: '最近12个月最严重风险状态',
                    dataIndex: 'seriousCondition',
                    render: text => {
                      return text || '-'
                    }
                  },
                  {
                    title: '最近6个月确认为黑名单的机构数',
                    dataIndex: 'blackOrgNum',
                    render: text => {
                      return text || '-'
                    }
                  }
                ]
                obj.dataSource = [
                  {
                    id: 1,
                    dimension: '手机号维度',
                    ...result.data.result.cellphoneDimension
                  },
                  {
                    id: 2,
                    dimension: '身份证维度',
                    ...result.data.result.idcardDimension
                  }
                ]
              } else {
                obj.items = Object.keys(result.data.result).map(item => ({
                  key: item,
                  label: YFMap[type] ? YFMap[type][item] : item,
                  children: YFMap[type]
                    ? YFMap[type][result.data.result[item]] || result.data.result[item] || '-'
                    : result.data.result[item] || '-'
                }))
              }
            } else {
              obj.items = [
                {
                  key: '查询失败',
                  label: '查询失败',
                  children: result.data.statusMsg
                }
              ]
            }
          } else {
            obj.items = [
              {
                key: '查询失败',
                label: '查询失败',
                children: result.data.resMsg
              }
            ]
          }

          return obj
        })
    ]
    setYFRiskControlReportItem(res)
  }

  const getRiskControlInfo = async () => {
    setIsLoading(true)
    const res = await GetRisk({
      order_sn: orderInfoRef.current.order_sn,
      deduction: tabKey,
      merchant_id: userInfo.merchant_id
    })
    setIsLoading(false)
    if (tabKey === '7' || tabKey === '17') {
      if (res) {
        if (res.data?.booleCredit?.resp_data?.url) {
          setJinDunRiskContral({ data: res.data.booleCredit.resp_data.url })
        } else {
          setJinDunRiskContral({ msg: '网络出错，请稍后再试' })
        }
      } else {
        setJinDunRiskContral({ msg: '风控额度不足,请充值' })
      }
    } else if (tabKey === '14') {
      if (res) {
        if (res.data?.liehuzuo_risk_report?.data?.status) {
          setLeihuzuoRiskContral({ data: res.data?.liehuzuo_risk_report?.data?.data?.report_url })
        } else {
          setLeihuzuoRiskContral({ msg: '报告正在生成中，请稍后再试' })
        }
      } else {
        setLeihuzuoRiskContral({ msg: '风控额度不足,请充值' })
      }
    } else if (res) {
      if (tabKey === '6') {
        if (res.creditXml?.data) {
          const xmlDom = createXml(res.creditXml.data)
          const reset = xmlFormat(xmlDom.documentElement.childNodes, xmlKey)
          setCreditData(reset)
          setCreditStatus({
            is_auth: 2,
            is_query: 3
          })
        } else {
          message.warning('网络出错，请稍后再试')
        }
      } else if (res.code === 200) {
        if (tabKey === '16') {
          if (res.data) {
            formatYfData(res.data.youfenData)
          }
        }
        setRiskControlData(res.data)
      }
    }
  }

  const formatTabs = riskList => {
    return tabItems.filter(i => i.key === '0' || riskList.includes(i.label))
  }

  return (
    <div className={styles.order_info}>
      {orderInfo ? <Tabs items={formatTabs(tabConfig)} onChange={setTabKey}></Tabs> : null}

      <Modal
        open={agreeModalFlag}
        title={
          <Space>
            <CheckCircleOutlined style={{ color: '#52c41a' }} />
            审核通过
          </Space>
        }
        okText='确认通过'
        cancelText='取消'
        okType='primary'
        centered
        onOk={() => {
          clearLoading()
          handleAudit(2)
        }}
        onCancel={() => setAgreeModalFlag(false)}
        destroyOnClose
      >
        <AgreeModalContent />
      </Modal>
    </div>
  )
}
